#include <windows.h>
#include "ImageProc.h"


//singlton
static ImageProcC* imageProc = NULL;

ImageProcC* ImageProcC::instance()
{
	if (imageProc == NULL)
	{
		imageProc = new ImageProcC();
	}
	return imageProc;
}

void ImageProcC::init()
{
	/* initialize camera */
    m_capture = cvCaptureFromCAM(2);
    if (m_capture)
	{
		m_frame = cvQueryFrame(m_capture);
		if (m_frame)
		{
			// Select parameters for Gaussian model.
			m_params = new CvGaussBGStatModelParams();						
			m_params->win_size=2;	
			m_params->n_gauss=5;
			m_params->bg_threshold=0.7;
			m_params->std_threshold=3.5;
			m_params->minArea=15;
			m_params->weight_init=0.05;
			m_params->variance_init=30; 

			// Creat CvBGStatModel
			// cvCreateGaussianBGModel( IplImage* first_frame, CvGaussBGStatModelParams* parameters )
			// or
			// cvCreateGaussianBGModel( IplImage* first_frame )
			m_bgModel = cvCreateGaussianBGModel(m_frame ,m_params);
			/* get video properties, needed by template image */
			/* create a windows */
			cvNamedWindow("BG", CV_WINDOW_AUTOSIZE);
			cvNamedWindow("FG", CV_WINDOW_AUTOSIZE);
		}
	}
}

void ImageProcC::update()
{
	if (m_capture)
	{
        /* get a frame */
        m_frame = cvQueryFrame(m_capture);
     
        /* always check */
        if (!m_frame) 
		{
			return;
		}
     
        // Update model
        cvUpdateBGStatModel(m_frame ,m_bgModel);
        
        // Display results
       	cvShowImage("BG", m_bgModel->background);
       	cvShowImage("FG", m_bgModel->foreground);	
	}
}

ImageProcC::ImageProcC()
{
	m_capture = NULL;
}

void ImageProcC::close()
{
    /* free memory */
    cvDestroyWindow("BG");
    cvDestroyWindow("FG");
	cvReleaseBGStatModel(&m_bgModel);
    cvReleaseCapture(&m_capture);
}